package com.pay.online.online_pay.alipay

import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import com.alipay.sdk.app.PayTask
import com.pay.online.online_pay.onlinepay.OnNotifyPayResultListener
import com.pay.online.online_pay.onlinepay.OnlinePayResultInfo
import com.pay.online.online_pay.onlinepay.OnlinePayResultType
import com.pay.online.online_pay.onlinepay.OnlinePayType

internal class AlipayPay private constructor() {

    companion object {

        private var alipay: AlipayPay? = null

        @JvmStatic
        fun getInstance(): AlipayPay? {
            if (alipay == null) {
                synchronized(AlipayPay::class.java) {
                    alipay = AlipayPay()
                }
            }
            return alipay
        }

    }

    private var onPayResultNotifyListener: OnNotifyPayResultListener? = null

    /** 设置通知支付结果的监听器 **/
    fun setOnNotifyPayResultListener(listener: OnNotifyPayResultListener) {
        this.onPayResultNotifyListener = listener
    }

    @Suppress("unchecked_cast")
    private val mHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0x0000A -> AlipayResultInfo(msg.obj as Map<String, String>).apply {
                    /** 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。 **/
                    val resultInfo = if (!TextUtils.isEmpty(result)) result else memo// 同步返回需要验证的信息
                    // 判断resultStatus 为9000则代表支付成功
                    val payResult = OnlinePayResultInfo().apply {
                        onlinePayType = OnlinePayType.Alipay
                        when {
                            TextUtils.equals(resultStatus, "9000") -> {
                                message = "支付宝支付成功"
                                resultType = OnlinePayResultType.Success
                            }
                            TextUtils.equals(resultStatus, "6001") -> {
                                message = "您取消了支付宝支付"
                                resultType = OnlinePayResultType.Canceled
                            }
                            else -> {
                                message = "支付失败，原因：$resultInfo"
                                resultType = OnlinePayResultType.Error
                            }
                        }
                    }
                    onPayResultNotifyListener?.onNotifyPayResult(payResult)
                }
            }
        }
    }

    /**
     * 支付宝发起支付
     * @param activity 上下文对象
     * @param orderInfo 订单信息，来自服务器
     */
    fun startPay(activity: Activity, orderInfo: String) {
        Thread {
            mHandler.sendMessage(Message().apply {
                what = 0x0000A
                obj = PayTask(activity).payV2(orderInfo, true)
            })
        }.start()
    }

}